﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Manga.Api.CCTuku
{
    using Core;
    using Core.Models;
    using System.ComponentModel;
    using System.Threading;
    using Windows.Storage.Streams;
    using Windows.UI.Xaml.Media.Imaging;

    partial class CCGallery : IImageProvider
    {
        #region Public Property
        public bool CanMoveToNext { get; private set; }

        public bool CanMoveToPrev { get; private set; }

        public string NextUri { get; private set; }

        public string PrevUri { get; private set; }

        public InMemoryRandomAccessStream ImageSrc { get; private set; }

        public bool CanMoveToNextEpisode { get; private set; }

        public string NextEpisodeUri { get; private set; }

        public bool CanMoveToPrevEpisode { get; private set; }

        public string PrevEpisodeUri { get; private set; }

        #endregion

        private const string ViewBar = @"//div[@class='viewBar']/div[1]/span";
        private const string ViewImage = @"//div[@id='showimage']/div/a/img";
        async public Task<bool> Move(string entry)
        {
            try
            {
                await Get(entry);
                var span = Multi(ViewBar);

                CanMoveToPrevEpisode = span[0].Attributes["href"].Value == "javascript:alert('已经是第一章');";
                PrevEpisodeUri = CanMoveToPrevEpisode ? span[0].Attributes["href"].Value : string.Empty;

                CanMoveToPrev = span[1].Attributes["href"].Value == "javascript:alert('已经是第一页');";
                PrevUri = CanMoveToPrev ? span[1].Attributes["href"].Value : string.Empty;

                CanMoveToNext = span[3].Attributes["href"].Value == "javascript:alert('已经是最后一页');";
                NextUri = CanMoveToNext ? span[3].Attributes["href"].Value : string.Empty;

                CanMoveToNextEpisode = span[span.Count - 1].Attributes["href"].Value == "javascript:alert('已经是最后一章');";
                NextEpisodeUri = CanMoveToNextEpisode ? span[span.Count - 1].Attributes["href"].Value : string.Empty;

                var src = Single(ViewImage).Attributes["src"].Value;
                var buffer = await Get(src, UriKind.RelativeOrAbsolute);
                var ms = new InMemoryRandomAccessStream();
                await ms.WriteAsync(buffer);
                ms.Seek(0);
                ImageSrc = ms;
                return true;
            }
            catch(Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return false;
            }
        }
    }
}
